﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Arich.Data.GenericNHDal;
using NHibernate;
using NHibernateDemo.DAL.Entity;
using NHibernate.Criterion;
//using NHibernate.Linq;
using System.Linq.Expressions;
using Arich.Data.GenericNHDal;

namespace NHibernateDemo.DAL {
    public class PersonBasicDAL : AbstractDataManageDal<PersonBasic,int> {
        

        public void SafeBatchAdd(IList<PersonBasic> persons) {
            NHibernateSessionManager.Instance.BeginTransaction( );
            foreach (var p in persons) {
                Save(p);
            }
            CommitChanges( );

        }

        

        public PersonBasic GetByFullName(string fullName) {
            var first = fullName.Split('_')[0];
            var last = fullName.Split('_')[1];
            return GetAll().Where(p=> p.Name.FirstName == first && p.Name.LastName == last).FirstOrDefault();
        }



        public void DeleteById(int Id) {
            var person = LoadById(Id);
            Delete(person);
            CommitChanges( );
        }



        public IList<PersonBasic> GetByFirstName(string name) {
            return GetByExample(new PersonBasic { Name = new Name { FirstName = name } });
            //return GetByCriteria(null,Restrictions.Eq("Name.FirstName", name)).SetCacheable(true).List<PersonBasic>( );
        }

        public IList<PersonBasic> GetByFirstNameAndAge(string name, int age) {
            //Example e = Example.Create(new PersonBasic { Name = new Name { FirstName = name }, Age = age })
            //                .EnableLike(MatchMode.Start)
            //                ;
            //return GetByCriteria(e).List<PersonBasic>();
            return GetAll( ).Where(p => p.Name.FirstName.StartsWith(name) && p.Age >= age).ToList( );

        }

        public IList<PersonBasic> GetByLastName(string name) {
            
            return  this.NHibernateSession.CreateQuery("from PersonBasic p where p.Name.LastName = :name")
                .SetString("name", name)
                .List<PersonBasic>( );
        }

       

        
    }
}
